package com.cliff.joinus;

import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.control.ActionListener;
import org.cybergarage.upnp.std.av.renderer.MediaRenderer;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class JoinusRenderer extends MediaRenderer implements ActionListener {

	protected HandlerThread threadBackground = null;
	protected Handler handlerBackground = null;
	protected static final int MESSAGE_STOP = 0;
	protected static final int MESSAGE_START = 1;
	protected static JoinusRenderer instance = null;;
	protected static final String TAG = "JoinusRenderer";

	protected JoinusRenderer() {
		this.setFriendlyName("JoinusRenderer");
		this.setManufacture("Cliff");
	}
	
	public synchronized static JoinusRenderer getInstance() {
		if (null == instance) {
			instance = new JoinusRenderer();
		}
		return instance;
	}

	protected static class BackgroundRendererHandler extends Handler {

		public BackgroundRendererHandler(Looper looper) {
			super(looper);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			JoinusRenderer renderer = JoinusRenderer.getInstance();
			switch (msg.what) {
			case MESSAGE_STOP:
				Log.d(TAG, "background BackgroundRendererHandler stop");
				renderer.stop();
				this.getLooper().quit();
				break;
			case MESSAGE_START:
				Log.d(TAG, "background BackgroundRendererHandler start");
				renderer.start();
				renderer.setActionListener(renderer);
				break;
			}
		}
	}

	public boolean startAtBackground() {
		synchronized (this) {
			// TODO Auto-generated method stub
			if (null != handlerBackground)
				return false;

			threadBackground = new HandlerThread("Renderer-Background");
			// threadBackground.setDaemon(true);
			threadBackground.start();
			handlerBackground = new BackgroundRendererHandler(
					threadBackground.getLooper());
			handlerBackground.sendEmptyMessage(MESSAGE_START);
			return true;
		}
	}

	public boolean stopAtBackground() {
		// TODO Auto-generated method stub
		synchronized (this) {
			if (null == handlerBackground)
				return false;

			handlerBackground.sendEmptyMessage(MESSAGE_STOP);
			handlerBackground = null;
			threadBackground = null;
			return true;
		}
	}

	@Override
	public boolean actionControlReceived(Action action) {
		// TODO Auto-generated method stub
		Log.d(TAG, "Renderer actionControlReceived():action="+action.toString());
		action.print();
		
		return false;
	}

}
